<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spuForm.spuName"></el-input>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select v-model="spuForm.tmId" placeholder="请选择品牌">
          <el-option
            v-for="(tm, index) in trademarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="SPU描述"
          v-model="spuForm.description"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-select
          v-model="saleAttrIdName"
          :placeholder="
            unUsedSaleAttrList.length > 0
              ? `还有${unUsedSaleAttrList.length}未选择`
              : `没有了!!!`
          "
        >
          <el-option
            :label="unUsedSaleAttr.name"
            v-for="(unUsedSaleAttr, index) in unUsedSaleAttrList"
            :key="unUsedSaleAttr.id"
            :value="`${unUsedSaleAttr.id}:${unUsedSaleAttr.name}`"
          >
          </el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" :disabled="!saleAttrIdName" @click="addSaleAttr">添加销售属性</el-button>

        <el-table border style="width: 100%" :data="spuForm.spuSaleAttrList">
          <el-table-column
            type="index"
            align="center"
            prop="prop"
            label="序号"
            width="80"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="150">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
               
              <el-tag
                v-for="(spuSaleAttrValue, index) in row.spuSaleAttrValueList"
                :key="spuSaleAttrValue.id"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index,1)"
              >
                {{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>
              
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.saleAttrValueName"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(row)"
                >+ 添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{row,$index}">
              <HintButton type="danger" icon="el-icon-delete" size="mini" title="删除销售属性" @click="spuForm.spuSaleAttrList.splice($index,1)"></HintButton>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

export default {
  name: "SpuForm",
  props: ["visible"],
  data() {
    return {
      dialogImageUrl: "", //预览大图当中的dialog内部的Img图片路径
      dialogVisible: false, //点击放大,弹出dialog
      saleAttrIdName: "",
      // 下面这三个数据不一定对
      // inputVisible: false,
      // inputValue: "",
      // spuForm目前初始化的对象是为了收集和展示添加时候的spu对象
      // 修改的时候,其实展示和收集的不是这个对象,是你请求回来赋值给spuForm的对象
      spuForm: {
        category3Id: 0,
        description: "",
        spuName: "",
        tmId: "",
        category3Id:'',
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "string",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
      }, //spu自己的销售属性列表
      spuImageList: [], //收集图片列表,先收集到这里,然后再整理到spuForm内部
      trademarkList: [],
      baseSaleAttrList: [], //所有的销售属性列表
    };
  },
  methods: {
    handleSuccess(res, file, fileList) {
      // console.log(res,file,fileList);
      this.spuImageList = fileList;
    },
    // 删除图片的时候,需要收集图片列表
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.spuImageList = fileList;
    },
    // 预览大图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 这个函数就是初始化请求数据的
    async getInitUpdateSpuFormData(row,category3Id) {
      // 根据ID获取spu详情信息
      this.category3Id = category3Id
      const result1 = await this.$API.spu.get(row.id);
      if (result1.code === 200 || result1.code === 2000) {
        this.spuForm = result1.data;
      }
      // 获取指定spu的id对应的图片列表
      const result2 = await this.$API.sku.getSpuImageList(row.id);
      if (result2.code === 200 || result2.code === 2000) {
        let spuImageList = result2.data;
        // 给图片全部都添加name和url
        spuImageList.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = spuImageList;
      }
      // 获取所有的品牌列表
      const result3 = await this.$API.trademark.getList();
      if (result3.code === 200 || result3.code === 2000) {
        this.trademarkList = result3.data;
      }
      // 获取所有的销售属性列表
      const result4 = await this.$API.spu.getSaleAttrList();
      if (result4.code === 200 || result4.code === 2000) {
        this.baseSaleAttrList = result4.data;
      }
    },
    // 点击添加请求数据
    async getInitAddSpuFormData(category3Id) {
      this.category3Id = category3Id
      // 获取所有的品牌列表
      const result3 = await this.$API.trademark.getList();
      if (result3.code === 200 || result3.code === 2000) {
        this.trademarkList = result3.data;
      }
      // 获取所有的销售属性列表
      const result4 = await this.$API.spu.getSaleAttrList();
      if (result4.code === 200 || result4.code === 2000) {
        this.baseSaleAttrList = result4.data;
      }
    },
    // 点击添加销售属性按钮
    addSaleAttr(){
      let [baseSaleAttrId,saleAttrName] = this.saleAttrIdName.split(':')

      let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList:[]
      }

      this.spuForm.spuSaleAttrList.push(obj)

      this.saleAttrIdName = ''
    },
    // 点击添加按钮切换为input
    showInput(row){
      // row.inputVisible = true
      this.$set(row,'inputVisible',true)
      this.$set(row,'saleAttrValueName','')
      this.$nextTick(()=>{
        this.$refs.saveTagInput.focus()
      })
    },
    // input失去焦点,把刚才收集的用户输入的数据,获取到,变为一个对象,添加到row.spuSaleAttrValueList当中
    handleInputConfirm(row) {
      let { saleAttrValueName, baseSaleAttrId } = row;
      // console.log(saleAttrValueName)
      let obj = { saleAttrValueName, baseSaleAttrId };

      //判断数据如果为空，不发请求
      if (saleAttrValueName.trim() === "") {
        row.saleAttrValueName = "";
        row.inputVisible = false
        return;
      }

      // 判断内容是否有重复
      let isRepeat = row.spuSaleAttrValueList.some(
        (item)=> item.saleAttrValueName === saleAttrValueName
      )
      if (isRepeat) {
        this.$message.success('属性值不能重复')
        row.saleAttrValueName = ''
        return
      }
      row.spuSaleAttrValueList.push(obj)


      // 清空当前input数据
      row.saleAttrValueName = ''
      // input 切换为 button
      row.inputVisible = false
    },
    // 点击保存操作
    async save(){
      let {spuForm,spuImageList,category3Id} = this
      spuForm.category3Id = category3Id

      spuForm.spuImageList = spuImageList.map((item)=>{
        return {
          imgName:item.name,
          imgUrl:item.imgUrl || item.response.data
        }
      })
      spuForm.spuSaleAttrList.forEach((item)=>{
        delete item.inputVisible
        delete item.saleAttrValueName
      })
      try {
        const result = await this.$API.spu.addUpdate(spuForm)
        if (result.code === 200 || result.code === 20000) {
          this.$message.success('保存spu成功')
          this.$emit('update:visible',false)
          // 再次触发另外一个自定义事件,告诉爹回来了
          this.$emit('backSuccess')
          // 清空data当中所有的数据
          this.resetData()
        }else{
          this.$message.error('保存spu失败')
        }
      } catch (error) {
        this.$message.error('保存spu请求失败')
      }
    },
    // 清空data的数据
    resetData(){
      this.dialogImageUrl = "" //预览大图当中dialog内部的img图片路径
      this.dialogVisible = false //点击方大弹出dialog
      this.saleAttrIdName = ""
      this.spuForm = {
        category3Id: 0,
        spuName: "",
        description: "",
        tmId: "",
        spuImageList: [],
        spuSaleAttrList: []//spu自己的销售属性列表
      }
      this.category3Id = ''
      this.spuImageList = [] //收集图片列表先收集到这里，然后最后再整理到spuForm内部
      this.trademarkList = []
      this.baseSaleAttrList = [] //所有的销售属性列表
    },
    // 取消操作
    cancel(){
      // 返回到父组件
      this.$emit('update:visible',false)
      // 清空数据
      this.resetData()
      // 清空父组件的标志位
      this.$emit('cancelBack')
    }
  },
  computed: {
    unUsedSaleAttrList() {
      // 从总的列表当中过滤和小得列表当中名字不一样的项
      return this.baseSaleAttrList.filter((item) => {
        return this.spuForm.spuSaleAttrList.every((item1) => {
          return item.name !== item1.saleAttrName;
        });
      });
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>